package data.trth;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipInputStream;

/**
 * Created by IntelliJ IDEA.
 * User: gderou
 * Date: 2 juin 2010
 * Time: 21:20:09
 * To change this template use File | Settings | File Templates.
 */
public class TRTHTradeExport {
    public static void main(String... args) throws Exception {
        GZIPInputStream gzIs = new GZIPInputStream(new BufferedInputStream(new FileInputStream(args[0])));
        BufferedReader r = new BufferedReader(new InputStreamReader(gzIs));
        String line;
        String currentProduct = "";
        FileWriter currentWriter = null;
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        int lineCounter = 0;

        String header = r.readLine(); // Ignore header data

        String currentDate = "";

        while ((line = r.readLine()) != null) {
            String[] strings = StringUtils.splitByWholeSeparatorPreserveAllTokens(line, ",");
            if (strings.length > 0) {
                if (!strings[0].equals(currentProduct) || !strings[1].equals(currentDate)) {
                    if (currentWriter != null) {
                        currentWriter.close();
                    }
                    currentProduct = strings[0];
                    currentDate = strings[1];
                    Date d = sdf.parse(currentDate);
                    File file = new File("history/" + DateFormatUtils.format(d, "yyyyMMdd") + "/" + getProductName(currentProduct) + ".csv");
                    file.getParentFile().mkdirs();
                    currentWriter = new FileWriter(file);
                    currentWriter.write(header);
                    currentWriter.write("\n");
                }
                currentWriter.write(line);
                currentWriter.write("\n");
            }

            lineCounter++;
            if (lineCounter % 10000 == 0) {
                System.out.println("Line : " + lineCounter);
            }

        }

        currentWriter.close();
    }

    static String getProductName(String code) {
        if (code.startsWith("FCE")) {
            return "CAC_FUT";
        } else if (code.startsWith("FDX")) {
            return "DAX_FUT";
        } else if (code.startsWith("STXE")) {
            return "STXE_FUT";
        }
        throw new RuntimeException("Unknown product");
    }
}
